package collection_try;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

public class ArrayListUnsafe {
    public static void main(String[] args) {
        // 创建一个非线程安全的ArrayList
        List<Integer> list = new ArrayList<>();


        // 创建多个线程，每个线程都向ArrayList中添加元素
        Runnable task = () -> {
            for (int i = 0; i < 1000; i++) {
                list.add(i); // 这里可能会引发ConcurrentModificationException或其他线程安全问题
            }
        };
        // ArrayList:
        Thread thread1 = new Thread(task);
        Thread thread2 = new Thread(task);

        // 启动线程
        thread1.start();
        thread2.start();

        try {
            // 等待线程执行完毕
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 打印ArrayList的大小和内容
        System.out.println("List size: " + list.size());
        System.out.println("List contents: " + list);


        // 创建一个vector
        List<Integer> listv = new Vector<>();

        Runnable taskv = () -> {
            for (int i = 0; i < 1000; i++) {
                listv.add(i);
            }
        };
        // Vector:
        Thread thread3 = new Thread(taskv);
        Thread thread4 = new Thread(taskv);

        thread4.start();
        thread3.start();

        try{
            thread3.join();
            thread4.join();
        }catch (InterruptedException e){
            e.printStackTrace();

        }
        System.out.println("Listv size: " + listv.size());
        System.out.println("Listv contents: " + listv);
    }
}
